
let lockfile = "app/var/run/cron.run"

let max_age_s = 16. *. 60.

(** check if there a lockfile younger than max_age *)
let has_fresh_lockfile now =
  let now_s = now |> Ptime.to_float_s in
  let file_s = lockfile |> File.mtime_0 in
  let age_s = now_s -. file_s in
  age_s < max_age_s

let process_queue ~base =
  Logr.info (fun m -> m "%s.%s" "Cron" "process_queue");
  let (let*%) = Http.(let*%) in
  let key_id = Ap.Person.my_key_id ~base in
  let*% pk = Ap.PubKeyPem.(private_of_pem pk_pem)
             |> Result.map_error (fun e -> (`Bad_gateway, [Http.H.ct_plain], (e |> Cgi.Response.body) ) ) in
  let now = Ptime_clock.now () in
  let key = Http.Signature.mkey ~now key_id pk in
  let%lwt r = Main.Queue.(once ~run_delay_s:1 (fun v ->
      lockfile |> File.touch;
      let%lwt r = process_new_and_due ~base ~key v in
      lockfile |> File.touch;
      Lwt.return r
    )) in
  r |> Lwt.return
